package core

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"os/exec"
	"strconv"
	"strings"

	"golang.org/x/net/websocket"
)

var contentArray = make([]string, 0, 5)

func getParam(param []byte) string {
	return string(param)
}

func CommandRun(script_index int, ws *websocket.Conn) error {
	config := GetConfig()[script_index]
	ssh, err := json.Marshal(config["ssh"])
	if err != nil {
		log.Fatal(err)
		return errors.New("-s parameter error.")
	}
	execute_script := fmt.Sprintf("%s/script/%s", GetRunPath(), "expect.py")
	params := make([]string, 0)
	params = append(params, execute_script)
	params = append(params, "-s")
	params = append(params, getParam(ssh))

	if len(config["git"]) != 0 {
		git, err := json.Marshal(config["git"])
		if err != nil {
			log.Fatal(err)
			return errors.New("-g parameter error.")
		}
		params = append(params, "-g")
		params = append(params, getParam(git))
	}

	if len(config["cmd"]) != 0 {
		cmdArray := make([]interface{}, 0)
		for _, cmd := range config["cmd"] {
			cmdArray = append(cmdArray, cmd)
		}
		cmdstr, err := json.Marshal(cmdArray)
		if err != nil {
			log.Fatal(err)
			return errors.New("-c parameter error.")
		}
		params = append(params, "-c")
		params = append(params, getParam(cmdstr))
	}

	cmdFd := exec.Command("python3", params...)
	log.Printf("执行命令: %s\n", strings.Join(cmdFd.Args[0:], " "))

	stdout, err := cmdFd.StdoutPipe()

	if err = cmdFd.Start(); err != nil {
		log.Println(err)
		return err
	}

	reader := bufio.NewReader(stdout)
	for {
		msg, err := reader.ReadString('\n')
		ws.Write([]byte(strconv.Itoa(script_index) + ":" + msg))
		if err != nil {
			if err == io.EOF {
				break
			} else {
				panic(err)
			}
		}
	}

	if err = cmdFd.Wait(); err != nil {
		log.Println(err)
		return err
	}

	return nil
}
